<?php

namespace app\index\controller;

use think\Request;
use app\index\model\Upload as UploadModel;

class Upload extends Base
{
    public function create(Request $request)
    {
        return $this->save_image($request);
    }

    public function save(Request $request)
    {
        return $this->save_image($request);
    }

    public function simditor(Request $request)
    {
        $file = $this->request->file('upfile');
        $upload_result = UploadModel::saveImage('content', $file, 1024);
        if($upload_result->status){
            $upload_data = $upload_result->data;
            $data = [
                'status' => true,
                'msg' => $upload_result->message,
                'file_path' => $upload_data['save_path'],
            ];
        }else{
            $data = [
                'status' => false,
                'msg' => $upload_result->message,
            ];
        }
        return json($data);
    }

    private function save_image($request)
    {
        $backcall = $request->param("backcall");
        $backcall_name = $request->param("backcall_name");
        $width = $request->param("width");
        $height = $request->param("height");
        $upload_type = $request->param("upload_type");
        $image = $request->param("image");
        $error_msg = '';

        if($request->isPost()){
            $file = $request->file('image');
            $upload_result = UploadModel::saveImage('avatar', $file, 300);
            if($upload_result->status){
                $data = $upload_result->data;
                $image = $data["save_path"];
            }else{
                $error_msg = $upload_result->message;
            }
        }

        $this->assign("backcall", $backcall);
        $this->assign("backcall_name", $backcall_name);
        $this->assign("width", $width);
        $this->assign("height", $height);
        $this->assign("image", $image);
        $this->assign("upload_type", $upload_type);
        $this->assign("error_msg", $error_msg);
        return $this->fetch('create');
    }
}
